//
//  AppDelegate.m
//  PackDemo
//
//  Created by 01 on 16/11/1.
//  Copyright © 2016年 蔡正军. All rights reserved.
//

#import "AppDelegate.h"
#import "JPUSHService.h"
#import "JSTHomeWebViewController.h"
#import "JSTAdWebViewController.h"
#import "KYNavigationController.h"
#import "KYTabBarController.h"
#import "SPKitExample.h"
#import <CommonCrypto/CommonCrypto.h>
#import <UserNotifications/UserNotifications.h>
#import "NSDictionary+KY.h"
#import "KYCacheManager.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h> 
#endif

@interface AppDelegate ()<UIAlertViewDelegate, UNUserNotificationCenterDelegate, JPUSHRegisterDelegate>
@property (nonatomic, strong) UIWindow *pushWindow;
@end

@implementation AppDelegate

int requestTime = 0;

#pragma mark - 创建单例对象(本身就是单例肯定要删除)
+ (AppDelegate *)currentAppDelegate {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

#pragma mark - UIApplication类
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 1.注册通知
    [self registNotify:application];
    
    // 2.配置极光推送(里面处理了http/https的处理)
    [self configJPush:launchOptions];
    
    // 3.处理推送消息
    [self processionPush:launchOptions];
    
    // 4.加载系统配置
    [self launchRootViewController];
    
    // 5.初始化IM组件
    [self setupIM];
    
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken{
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    if(notification != nil){
        //本地通知参数
        self.pushDict = [notification.userInfo valueForKey:@"notificationKey"];
        if (IsArrEmpty(self.pushDict)) self.pushDict = notification.userInfo;
        
        //统计推送到达率
        [JSTServer requestPushArrivalRateData:[self.pushDict valueForKey:@"id"] push:^(NSDictionary *pushArrivalRateData) {
        }];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

#pragma mark - 切换横竖屏
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (self.currentScreenStatus) return UIInterfaceOrientationMaskAll;
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //统计推送到达率
        [JSTServer requestPushArrivalRateData:[userInfo valueForKey:@"id"] push:^(NSDictionary *pushArrivalRateData) {
        }];
        //处理远程推送
        if (self.reloadFinish) {
            [self goToMssageViewControllerWith:userInfo];
        }
    }
    completionHandler(); // 系统要求执这个法
}

/**
 *  根据通知类型进入不同的控制器
 *
 *  @param remoteNotification 通知内容
 */
- (void)goToMssageViewControllerWith:(NSDictionary *)remoteNotification{
    if (IsStrEmpty(remoteNotification[@"link"])) return;
    JSTAdWebViewController *pushViewCtl = [[JSTAdWebViewController alloc] init];
    pushViewCtl.pushData = remoteNotification;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:pushViewCtl];
    [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - Private method(私有方法)
/**
 *  注册通知
 *
 *  @param application UIApplication
 */
- (void)registNotify:(UIApplication *)application{
    CGFloat version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:UNAuthorizationOptionCarPlay | UNAuthorizationOptionSound | UNAuthorizationOptionBadge | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@" iOS 10 request notification success");
            }else{
                NSLog(@" iOS 10 request notification fail");
            }
        }];
    }else{
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert categories:nil];
        [application registerUserNotificationSettings:setting];
    }
    //注册通知
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

/**
 *  处理极光推送
 *
 *  @param launchOptions 启动所传递的参数
 */
- (void)configJPush:(NSDictionary *)launchOptions{
    //注册http、https监控
    [NSURLProtocol registerClass:[JSTURLProtocol class]];
    //让图片加载支持https
    [[SDWebImageManager sharedManager].imageDownloader setValue: nil forHTTPHeaderField:@"Accept"];
    NSString *JPushAppKey = [KYSystemConfigModel shareInstance].appConfig.systemModel.jpush_appkey;
    if (!IsStrEmpty(JPushAppKey)) {
        JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
        [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey channel:@"App store" apsForProduction:YES];
    }
}

#pragma mark - launchOptions根据不同的通知类型启动程序
- (void)processionPush:(NSDictionary *)launchOptions {
    UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    
    //通过本地通知启动
    if(localNotification){
        self.pushDict = localNotification.userInfo;
    }
    NSDictionary *remoteCotificationDic = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    //远程通知启动
    if(remoteCotificationDic){
        self.pushDict = remoteCotificationDic;
    }
}

#pragma mark - 进入主控制器
- (void)launchRootViewController {
    //配置根控制器
    [self configRootController];
    
    //统计安装量和日活
    [JSTServer postAPPInstallDataSuccess:nil err:nil];
}

- (void)configRootController {
    
    // 设置根控制器
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    KYTabBarController *tabbarVc = [[KYTabBarController alloc] init];
    self.window.rootViewController = tabbarVc;
    [self.window makeKeyAndVisible];
    
    // 存储app安装时间
    [JSTSystemInfo saveAppInstallTime];
    
    // 上传V参数获取配置广告等参数
    [self postAppInfo];
}

/**
 初始化IM控件
 */
- (void)setupIM{
    [[SPKitExample sharedInstance] callThisInDidFinishLaunching];
    [[SPKitExample sharedInstance] callThisAfterISVAccountLoginSuccessWithYWLoginId:[[KYUserAccountTool shareUserData].userPhone MD5] passWord:[@"123456" MD5] preloginedBlock:nil successBlock:^{
        self.taobaoIMLogin = YES;
    } failedBlock:^(NSError *error) {
        self.taobaoIMLogin = NO;
    }];
}
/**
 *  获取配置信息
 */
- (void)postAppInfo{
    [JSTServer requestAPPInfoDataSuccess:^(NSDictionary *successDic) {
        KYSystemConfigModel *model = [[KYSystemConfigModel shareInstance] refreshDateWithDict:successDic];
        KYCacheManager *manager = [KYCacheManager shareInstance];
        [manager ky_setObject:model forKey:KYSystemCongfig];
        NSDictionary *systemDic     = successDic[@"data"][@"app_config"][@"system_value"];
        [JSTSystemInfo saveToken:systemDic[@"token"]];
        NSString *appInfoStatus = [NSString stringWithFormat:@"%@",successDic[@"status"]];
        if (![appInfoStatus isEqualToString:@"1"]) return;
        //1.处理广告过滤接口
        NSString *advertStatusStr = [NSString stringWithFormat:@"%@",successDic[@"data"][@"adv_restrictions"][@"status"]];
        if ([advertStatusStr isEqualToString:@"1"]) {
            NSArray *arr  = successDic[@"data"][@"adv_restrictions"][@"newvalue"];
            for (int i = 0; i < arr.count; i++) {
                [kFilteredDic setValue:[arr[i] valueForKey:@"key"] forKey:[arr[i] valueForKey:@"value"]];
                [kFilteredStr addObject:[arr[i] valueForKey:@"value"]];
            }
        }
        //2.app配置信息
        NSString *configStatusStr = [NSString stringWithFormat:@"%@",successDic[@"data"][@"app_config"][@"status"]];
        if ([configStatusStr isEqualToString:@"1"]) {
            NSDictionary *configureData = successDic[@"data"][@"app_config"];
            // 分类处理回调数据
            NSDictionary *systemDic     = [configureData valueForKey:@"system_value"];
            NSDictionary *shareDic      = [configureData valueForKey:@"share_value"];
            NSDictionary *readerDic     = [configureData valueForKey:@"reader_value"];
            NSDictionary *configDic     = [configureData valueForKey:@"config"];
            NSDictionary *functionDic     = [configureData valueForKey:@"app_function"];
            // 分配新的内存空间
            NSMutableDictionary *mSystemDic     = [NSMutableDictionary dictionary];
            NSMutableDictionary *mShareDic      = [NSMutableDictionary dictionary];
            NSMutableDictionary *mReaderDic     = [NSMutableDictionary dictionary];
            NSMutableDictionary *mConfigDic     = [NSMutableDictionary dictionary];
            NSMutableDictionary *mFunctionDic     = [NSMutableDictionary dictionary];
            if (!IsArrEmpty(systemDic)) {
//               mShareDic  [systemDic deleteAllNullValue];
                [mSystemDic setDictionary:[systemDic deleteAllNullValue]];
//                [systemDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//                    [mSystemDic setValue:[JSTSystemInfo getStr:obj] forKey:key];
//                }];
            }
            if (!IsArrEmpty(shareDic)) {
                [shareDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    [mShareDic setValue:[JSTSystemInfo getStr:obj] forKey:key];
                }];
            }
            if (!IsArrEmpty(readerDic)) {
                [readerDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    [mReaderDic setValue:[JSTSystemInfo getStr:obj] forKey:key];
                }];
            }
            if (!IsArrEmpty(configDic)) {
                [configDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    [mConfigDic setValue:[JSTSystemInfo getStr:obj] forKey:key];
                }];
            }
            if (!IsArrEmpty(functionDic)) {
              [mFunctionDic setDictionary:[functionDic deleteAllNullValue]];
            }
            // 将处理后的数据存储 并设为全局
            [JSTSystemInfo getSystemConfig:mSystemDic];
            [JSTSystemInfo getShareConfig:mShareDic];
            [JSTSystemInfo getReaderConfig:mReaderDic];
            [JSTSystemInfo getqrConfig:mConfigDic];
            [JSTSystemInfo getFunctionConfig:mFunctionDic];
            if ([JSTSystemInfo isLoadTabbar]) {
//                _tabBarController = [[JSTTabBarViewController alloc]init];
//                _tabBarController.tabBar.hidden = YES;
//                self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//                self.window.rootViewController = _tabBarController;
                [self.window makeKeyAndVisible];
            }
        }
        //3.版本更新信息，企业证书失效暂停使用
        /*
        NSString *versionStatusStr = [NSString stringWithFormat:@"%@",successDic[@"data"][@"update_ver"][@"status"]];
        if ([versionStatusStr isEqualToString:@"1"]) {
            NSString *update = [NSString stringWithFormat:@"%@",successDic[@"data"][@"update_ver"][@"update_status"]];
            if ([update isEqualToString:@"1"]) {
                self.stopOpenHomepage = YES;
                NSString *updateUrl = successDic[@"data"][@"update_ver"][@"update_url"];
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"检测到版本更新" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"升级" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSString *urlString = updateUrl;
                    NSURL *url  = [NSURL URLWithString:urlString];
                    [[UIApplication sharedApplication] openURL:url];
                }];
                [alertVC addAction:action];
                [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
            }
        }
         */
        //4.广告位信息
        NSArray *advertInfoData = successDic[@"data"][@"zone"];
        NSMutableDictionary *typeDic =      [NSMutableDictionary dictionary];
        NSMutableArray      *adidArr =      [NSMutableArray array];
        BOOL                hasOpenAdvert   = NO;
        BOOL                hasCrossAdvert  = NO;
        if (!IsArrEmpty(advertInfoData)) {
            for (int i = 0; i < advertInfoData.count; i++) {
                NSDictionary *dic = advertInfoData[i];
                //广告类型ID
                NSString *typeId = [NSString stringWithFormat:@"%@", [dic valueForKey:@"adtplid"]];
                //广告位ID
                NSString *adid = [NSString stringWithFormat:@"%@", [dic valueForKey:@"zoneid"]];
                [typeDic setValue:typeId forKey:adid];
                [adidArr addObject:adid];
                //存储adid、typeid数据
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setValue:typeDic forKey:@"typeId"];
                [userDefaults setValue:adidArr forKey:@"adidDic"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                //缓存开屏数据
                if ([typeId isEqualToString:@"1000"]){
                    hasOpenAdvert = YES;
                    //发送请求获取广告数据
                    [JSTServer requestAdvert:adid dataDic:^(NSDictionary *dataDic) {
                        NSDictionary *dic = dataDic[@"data"];
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        NSMutableDictionary *customDic = [NSMutableDictionary dictionary];
                        [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                            [customDic setValue:[NSString stringWithFormat:@"%@", [dic valueForKey:key]] forKey:key];
                        }];
                        [userDefaults setValue:customDic forKey:@"tableScreenData"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [JSTFMDBManager insertOrUpdateModelToDatabase:[JSTStartViewData modelWith:@"tableScreen" adImgUrl:[dic valueForKey:@"imageurl"] disseminateImgUrl:[dic valueForKey:@"app_ads"]]];
                        UIImageView *imgView = [[UIImageView alloc] init];
                        [imgView sd_setImageWithURL:[NSURL URLWithString:[dic valueForKey:@"imageurl"]] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
                        UIImageView *imgView1 = [[UIImageView alloc] init];
                        [imgView1 sd_setImageWithURL:[NSURL URLWithString:[dic valueForKey:@"app_ads"]] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
                        if (self.startViewNeedOpen) {
                            [[JSTHomeWebViewController shareHomeVC] createStartView];
                        }
                    } errorStr:^(NSString *error, NSInteger status) {
                    }];
                }
                //缓存插屏数据
                if ([typeId isEqualToString:@"21"]) {
                    hasCrossAdvert = YES;
                    [JSTServer requestAdvert:adid dataDic:^(NSDictionary *dataDic) {
                        NSDictionary *dic = dataDic[@"data"];
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        NSMutableDictionary *customDic = [NSMutableDictionary dictionary];
                        [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop){
                             [customDic setValue:[NSString stringWithFormat:@"%@", [dic valueForKey:key ]] forKey:key];
                         }];
                        [userDefaults setValue:customDic forKey:@"crossScreenData"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [JSTFMDBManager insertOrUpdateModelToDatabase:[JSTTableScreenData modelWith:@"crossScreen" getImgUrl:[dic valueForKey:@"imageurl"]]];
                        UIImageView *imgView = [[UIImageView alloc] init];
                        [imgView sd_setImageWithURL:[NSURL URLWithString:[dic valueForKey:@"imageurl"]]];
                    } errorStr:^(NSString *error, NSInteger status) {
                    }];
                }
            }
            //cps广告scheme信息
            NSString *schemeStatus = [NSString stringWithFormat:@"%@",successDic[@"data"][@"scheme"][@"status"]];
            if ([schemeStatus isEqualToString:@"1"]) {
                NSArray *schemeInfoArr = successDic[@"data"][@"scheme"][@"data"];
                NSMutableArray *schemeArr = [NSMutableArray array];
                for (NSDictionary *dic in schemeInfoArr) {
                    [schemeArr addObject:dic[@"value"]];
                }
                [[NSUserDefaults standardUserDefaults] setObject:schemeArr forKey:@"payScheme"];
            }
            //检查app状态
            [self checkAppStatus];
            //不含有开屏广告位清空缓存
            if (!hasOpenAdvert) {
                [JSTFMDBManager deleteModelInDatabase:[JSTStartViewData modelWith:nil adImgUrl:nil disseminateImgUrl:nil]];
            }
            //不含有插屏广告位清空缓存
            if (!hasCrossAdvert) {
                [JSTFMDBManager deleteModelInDatabase:[JSTTableScreenData modelWith:nil getImgUrl:nil]];
            }
        }
    } err:^(NSString *errStr) {
        requestTime ++;
        if (requestTime<=3) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self postAppInfo];
            });
        }else{
            //检查app状态
            [self checkAppStatus];
        }
    }];
//    [[JSTLocation sharedInstace] requestAddress:^{}];
}

/**
 *  检查app状态
 */
- (void)checkAppStatus {
    if (![JSTSystemInfo appStatus]) {
        self.stopOpenHomepage = YES;
        NSString *msg = [JSTSystemInfo appStatusMsg];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            exit(0);
        }];
        [alertVC addAction:action];
        [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
    }
}

#pragma mark - NO
- (void)loadRootViewController:(UIViewController *)viewCtl {
    UINavigationController *navCtl = [[UINavigationController alloc] initWithRootViewController:viewCtl];
    self.window.rootViewController = navCtl;
}

- (NSString *)MD5WithData:(NSData *)data{
    unsigned char result[16];
    CC_MD5( [data bytes], (CC_LONG)[data length], result ); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
@end
